package com.siyoumi.app.modules.file.admin;

import com.siyoumi.app.modules.file.service.FileService;
import com.siyoumi.controller.AdminApiController;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.util.XFile;
import com.siyoumi.util.XReturn;
import com.siyoumi.component.http.InputData;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/xadmin/file/file__edit")
public class file__edit
        extends AdminApiController {
    @GetMapping()
    public XReturn index() {
        String filename = input("filename");
        String dir = input("dir");

        setPageTitle(filename, "-编辑");
        FileService app = FileService.getBean();
        String handlerDir = app.getHandlerDir(dir, filename);
        if (!XFile.exists(handlerDir)) {
            return EnumSys.FILE_EXISTS.getR();
        }

        String txt = XFile.getContent(handlerDir);
        Map<String, Object> data = new HashMap<>();
        data.put("filename", filename);
        data.put("dir", dir);
        data.put("txt", txt);
        getR().setData("data", data);

        setPageInfo("encode_key", app.getAesKey());
        setPageInfo("encode_vi", app.getAesVi());

        return getR();
    }


    @Transactional
    @PostMapping("/save")
    public XReturn save() {
        return FileService.getBean().edit(InputData.fromRequest());
    }
}
